﻿using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using MusicFluent.Models;
using MusicFluent.MusicViews;
using MusicFluent.ViewModels;
using MusicFluent.Views;
using NetEasyMusic.Lib.Data;
using NetEasyMusic.Lib.Models;

namespace MusicFluent.Controls;

public partial class SongSimpleControl : UserControl
{
    private SongModel _model;

    public SongSimpleControl(SongModel model)
    {
        InitializeComponent();
        _model = model;
        NameBlock.Text = model.Name;
    }

    protected override void OnInitialized()
    {
        Image.Source = $"{_model.PicUrl}?param=30y30";
        var context = string.IsNullOrEmpty(_model.Album) ? _model.Artists.FirstOrDefault()?.Name : _model.Album;
        if (string.IsNullOrEmpty(context))
        {
            ArtistButton.IsDefault = true;
            return;
        }
        ArtistButton.Content = context;
    }

    private async void MusicDoubleTapped(object? sender, TappedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        if (string.IsNullOrEmpty(_model.Time))
        {
            using var music = new Music(view.Cookie);
            _model = await music.GetSongFormId(_model.Id);
        }

        view.SongPanel.DataContext = _model;
        if (view.DataContext is not MainWindowViewModel model) return;
        model.Add(ViewOpera.GetList(this));
        model.PlayChange(_model.Id);
    }

    private void ArtistClick(object? sender, RoutedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        if (string.IsNullOrEmpty(_model.Album))
        {
            var artist = _model.Artists.FirstOrDefault();
            if (artist == null) return;
            var artistView = new ArtistView(artist, view.Cookie);
            view.Navigate(artistView);
            return;
        }

        var album = new AlbumView(_model.AlbumId);
        view.Navigate(album);
    }

    private void AddItemClick(object? sender, RoutedEventArgs e)
    {
        var model = ViewOpera.GetViewData<MainWindowViewModel>(Parent);
        model?.Add(_model);
    }

    private void PlayClick(object? sender, RoutedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        view.SongPanel.DataContext = _model;
        if (view.DataContext is not MainWindowViewModel model) return;
        model.Add(ViewOpera.GetList(this));
        model.PlayChange(_model.Id);
    }

    private void DetailClick(object? sender, RoutedEventArgs e)
    {
    }
}